﻿using System;
using System.Threading.Tasks;
using Consul;

public class ServiceRegistration
{
    private readonly ConsulClient _consulClient;

    public ServiceRegistration(string consulAddress = "localhost", int consulPort = 8500)
    {
        _consulClient = new ConsulClient(config =>
        {
            config.Address = new Uri($"http://{consulAddress}:{consulPort}");
        });
    }

    public async Task RegisterAsync(string serviceId, string serviceName, string serviceAddress, int servicePort, Uri healthCheckUrl)
    {
        var registration = new AgentServiceRegistration
        {
            ID = serviceId,
            Name = serviceName,
            Address = serviceAddress,
            Port = servicePort,
            Check = new AgentServiceCheck
            {
                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(30),
                HTTP = healthCheckUrl.ToString(),
                Interval = TimeSpan.FromSeconds(10),
                Timeout = TimeSpan.FromSeconds(5)
            }
        };

        await _consulClient.Agent.ServiceRegister(registration);
        Console.WriteLine($"Service {serviceName} registered with Consul.");
    }
}
